<?php
use think\Db;
use yzx\Ucpaas;
use aldy\SmsDemo;
use PHPMailer\Sendmail;


function api($name,$vars=array()){
    $array     = explode('/',$name);
    $method    = array_pop($array);
    $classname = array_pop($array);
    $module    = $array? array_pop($array) : 'common';
    $callback  = 'app\\'.$module.'\\Api\\'.$classname.'Api::'.$method;
    if(is_string($vars)) {
        parse_str($vars,$vars);
    }
    return call_user_func_array($callback,$vars);
}



function get_config_group($group=0){
    $list = config('config_group_list');
    return $group?$list[$group]:'';
}


function get_config_type($type=0){
    $list = config('config_type_list');  
    return $list[$type];
}


function alisms($phoneNum,$code){
    header('Content-Type: text/plain; charset=utf-8');
    $Alidy = new SmsDemo();
    $result = $Alidy->sendSms($phoneNum,config('alidy.SignName'),config('alidy.TemplateCode'),$code);
    $result = object_array($result);
    return $result;
}


function GetRandCode($len = 6)
{
    $chars = array(
        "1", "2",
        "3", "4", "5", "6", "7", "8", "9"
    );
    $charsLen = count($chars) - 1;
    shuffle($chars);
    $output = "";
    for ($i=0; $i<$len; $i++)
    {
        $output .= $chars[mt_rand(0, $charsLen)];
    }
    return $output;
}



function delete_dir_file($path, $del = true){
    $result = false;
    if(is_dir($path)) {
        $path = iconv ("UTF-8" , "GBK" , $path);
        $handle = opendir ($path);
        if ( $handle ) {
            while (false !== ($item = readdir ($handle))) {
                if ( ($item != ".") && ($item != "..") ) {
                    is_dir ("$path/$item") ? delete_dir_file ("$path/$item" , $del) : unlink ("$path/$item");
                }
            }
            closedir ($handle);
            if ( $del ) {
                rmdir ($path);
            }
            $result = true;
        }
    }
    return $result;
}


function uuid($prefix = '')
{
    $chars = md5(uniqid(mt_rand(), true));
    return $prefix . $chars;
}


function exportExcel($name,$title,$cellName,$data)
{
    vendor("PHPExcel.PHPExcel");
    $objPHPExcel = new \PHPExcel();
    $topNumber = 2;
    $xlsTitle = iconv('utf-8', 'gb2312', $title);
    $fileName = $title.date('_YmdHis');
    $cellKey = array(
        'A','B','C','D','E','F','G','H','I','J','K','L','M',
        'N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
        'AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM',
        'AN','AO','AP','AQ','AR','AS','AT','AU','AV','AW','AX','AY','AZ'
    );

    $objPHPExcel->getActiveSheet()->mergeCells('A1:'.$cellKey[count($cellName)-1].'1');
    $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1',$name);
    $objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setBold(true);
    $objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setSize(18);
    $objPHPExcel->getActiveSheet()->getStyle('A1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
    $objPHPExcel->getActiveSheet()->getStyle('A1')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);

    foreach ($cellName as $k=>$v)
    {
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue($cellKey[$k].$topNumber, $v[1]);
        $objPHPExcel->getActiveSheet()->getStyle($cellKey[$k].$topNumber)->getFont()->setBold(true);
        $objPHPExcel->getActiveSheet()->getStyle($cellKey[$k].$topNumber)->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);//垂直居中
        if($v[2] > 0)//大于0表示需要设置宽度
        {
            $objPHPExcel->getActiveSheet()->getColumnDimension($cellKey[$k])->setWidth($v[2]);
        }
    }
    foreach ($data as $k=>$v)
    {
        foreach ($cellName as $k1=>$v1)
        {
            $objPHPExcel->getActiveSheet()->setCellValue($cellKey[$k1].($k+1+$topNumber), $v[$v1[0]]);
            if($v1[3] != "" && in_array($v1[3], array("LEFT","CENTER","RIGHT")))
            {
                $v1[3] = eval('return PHPExcel_Style_Alignment::HORIZONTAL_'.$v1[3].';');
                $objPHPExcel->getActiveSheet()->getStyle($cellKey[$k1].($k+1+$topNumber))->getAlignment()->setHorizontal($v1[3]);
            }
        }
    }
    header('pragma:public');
    header('Content-type:application/vnd.ms-excel;charset=utf-8;name="'.$xlsTitle.'.xls"');
    header("Content-Disposition:attachment;filename=$fileName.xls");//attachment新窗口打印inline本窗口打印
    $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
    $dir = ROOT_PATH . 'public' . DS . 'excel';
    if(!file_exists($dir)){
        mkdir($dir, 0700,true);
    }
    $filePath = 'excel/'.$fileName.'.xls';
    $objWriter->save($filePath);
    return ['code'=>200,'msg'=>'/'.$filePath];
}

function object_array($array) {
    if(is_object($array)) {
        $array = (array)$array;
    } if(is_array($array)) {
        foreach($array as $key=>$value) {
            $array[$key] = object_array($value);
        }
    }
    return $array;
}


function https_request($url, $data = '', $method = 'GET', $header = '')
{
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    if ($header) {
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        curl_setopt($curl, CURLOPT_HEADER, 0);
    } else {
        curl_setopt($curl, CURLOPT_HEADER, 0);
    }
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
    if ($method == 'POST') {
        curl_setopt($curl, CURLOPT_POST, 1);
        if ($data != '') {
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
    }
    curl_setopt($curl, CURLOPT_TIMEOUT, 30);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $tmpInfo = curl_exec($curl);
    curl_close($curl);
    return $tmpInfo;
}


function http_type(){
    $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
    return  $http_type . $_SERVER['HTTP_HOST'];
}


function base64_img($base64url,$bool = false)
{
    $base64url = str_replace (' ' , '+' , $base64url);
    if ( preg_match ('/^(data:\s*image\/(\w+);base64,)/' , $base64url , $result) ) {
        $type = $result[ 2 ];
        $new_file = ROOT_PATH . 'public' . DS . 'uploads/face/' . date ('Ymd' , time ()) . "/";
        if ( !file_exists ($new_file) ) {
            mkdir ($new_file , 0700,true);
        }
        $new = md5 (time ().uuid());
        $new_file = $new_file . $new . ".{$type}";
        if ( file_put_contents ($new_file , base64_decode (str_replace ($result[ 1 ] , '' , $base64url))) ) {

            $file_name =  "/uploads/face/" . date ('Ymd' , time ()) . "/" . $new . ".{$type}";
            return ['code'=>200,'msg'=>$file_name];
        } else {
            return ['code'=>100,'msg'=>''];
        }
    }
}
function base64EncodeImage ($image_file) {
    $base64_image = '';
    $image_info = getimagesize($image_file);
    $image_data = file_get_contents($image_file);
    $base64_image = base64_encode($image_data);
    return $base64_image;
}




function getKdApiSearch($ShipperCode,$LogisticCode,$OrderCode = ''){
    $requestData= "{'OrderCode':'".$OrderCode."','ShipperCode':'".$ShipperCode."','LogisticCode':'".$LogisticCode."'}";
    $datas = array(
        'EBusinessID' => '1467058',//商户id
        'RequestType' => '1002',
        'RequestData' => urlencode($requestData) ,
        'DataType' => '2',
        'DataSign' => urlencode(base64_encode(md5($requestData.'6877db6c-c961-4b8a-8c13-c00011480971')))//签名
    );
    foreach ($datas as $key => $value) {
        $temps[] = sprintf('%s=%s', $key, $value);
    }
    $post_data = implode('&', $temps);
    $url_info = parse_url('https://api.kdniao.com/Ebusiness/EbusinessOrderHandle.aspx');//api接口
    if(empty($url_info['port']))
    {
        $url_info['port']=80;
    }
    $httpheader = "POST " . $url_info['path'] . " HTTP/1.0\r\n";
    $httpheader.= "Host:" . $url_info['host'] . "\r\n";
    $httpheader.= "Content-Type:application/x-www-form-urlencoded\r\n";
    $httpheader.= "Content-Length:" . strlen($post_data) . "\r\n";
    $httpheader.= "Connection:close\r\n\r\n";
    $httpheader.= $post_data;
    $fd = fsockopen($url_info['host'], $url_info['port']);
    fwrite($fd, $httpheader);
    $gets = "";
    $headerFlag = true;
    while (!feof($fd)) {
        if (($header = @fgets($fd)) && ($header == "\r\n" || $header == "\n")) {
            break;
        }
    }
    while (!feof($fd)) {
        $gets.= fread($fd, 128);
    }
    fclose($fd);
    return $gets;
}



function generateTree($array,$son = 'children',$pid = 'pid',$id = 'id'){
    $items = array();
    foreach($array as $value){
        $items[$value[$id]] = $value;
    }
    $tree = array();
    foreach($items as $key => $item){
        if(isset($items[$item[$pid]])){
            $items[$item[$pid]][$son][] = &$items[$key];
        }else{
            $tree[] = &$items[$key];
        }
    }
    return $tree;
}


function get_time($targetTime)
{
    $todayLast = strtotime(date('Y-m-d 23:59:59'));
    $agoTime = $todayLast - $targetTime;
    $agoDay = floor($agoTime / 86400);
    if ($agoDay == 0) {
        $result = '今天 ' . date('H:i', $targetTime);
    } elseif ($agoDay == 1) {
        $result = '昨天 ' . date('H:i', $targetTime);
    }else {
        $result = date("Y/m/d H:i", $targetTime);
    }
    return $result;
}


/*
 * 淘宝接口：根据ip获取所在城市名称
 */
function get_ip_area($ip){
    if($ip == '127.0.0.1'){
        return '内网IP';
    }
    $url = "http://ip.taobao.com/service/getIpInfo.php?ip={$ip}";
    $ret = https_request($url);
    $arr = json_decode($ret,true);
    if($arr['code'] != 0){
        return '';
    }else{
        return $arr['data']['country'].$arr['data']['region'].$arr['data']['city'].$arr['data']['isp'];
    }
    //-------------获取商品的真实价格---------------
}
function Qrcode($content,$logo = ""){
    import('org.phpqrcode', EXTEND_PATH);
    $date = date('Ymd');
    $dir = ROOT_PATH . 'public' . DS . 'uploads/ercode/'.$date;
    $url =  http_type ();
    if(!file_exists($dir)){
        mkdir($dir, 0700,true);
    }
    $name = md5(time().uuid()).".png";
    $value = "$content";
    $errorCorrectionLevel = 'M';
    $matrixPointSize = 6;
    //组装图片路径
    $filepath= $dir.DS.$name;
    \QRcode::png($value,$filepath , $errorCorrectionLevel, $matrixPointSize, 2);
    $QR = $filepath;
    if ($logo && file_exists($logo)) {
        $QR = imagecreatefromstring(file_get_contents($QR));
        $logo = imagecreatefromstring(file_get_contents($logo));
        $QR_width = imagesx($QR);
        $QR_height = imagesy($QR);
        $logo_width = imagesx($logo);
        $logo_height = imagesy($logo);
        $logo_qr_width = $QR_width / 4;
        $scale = $logo_width/$logo_qr_width;
        $logo_qr_height = $logo_height/$scale;
        $from_width = ($QR_width - $logo_qr_width) / 2;
        imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width,$logo_qr_height, $logo_width, $logo_height);
        $newname = 'uploads/ercode/'.$date.DS.md5(time().uuid()).".png";
        imagepng($QR, ROOT_PATH . 'public' . DS .$newname);
        unlink($filepath);
        imagedestroy($QR);
        imagedestroy($logo);
        return $url.DS.$newname;
    }else{
        $QR = imagecreatefromstring(file_get_contents($QR));
        imagedestroy($QR);
        return "/uploads/ercode/".$date."/".$name;
    }
}
//-------------------------------------------------------------------------------------------
/**
 * 卡证识别
 * @param $url
 * @param $type：1身份证正面  2身份证反面（有效期那面） 3营业执照
 * @return bool|mixed
 */
 function getImgInfoForWx($url,$type,$image){
    $token = baiduToken();
    $url = "{$url}?access_token={$token}";
    $bodys = array(
        'url' => $image
    );
    if($type == 1) $bodys['id_card_side'] = 'front';
    if($type == 2) $bodys['id_card_side'] = 'back';
    $res = request_post($url, $bodys);
    $res = json_decode($res,true);
    if(isset($res['error_code'])){
        return '';
    }else{
        return $res['words_result'];
    }
}
 function baiduToken()
{
    header('Access-Control-Allow-Origin: *');
    $today = date('Y-m-d');
    $today_20 = date('Y-m-d',time()+20*3600*24);
    $tokenInfo = Db::table('up_token')->where('id',4)->find();
    if(!$tokenInfo['token'] || $tokenInfo['tdate'] < $today){
        $url = 'https://aip.baidubce.com/oauth/2.0/token';
        $post_data['grant_type']       = 'client_credentials';
        $post_data['client_id']      = 'GWrgHIFvn7VB5jnBhplySGmH';
        $post_data['client_secret'] = '3sGDjVtp3larEYTP7aoVjOfFCnvQSB26';
        $o = "";
        foreach ( $post_data as $k => $v )
        {
            $o.= "$k=" . urlencode( $v ). "&" ;
        }
        $post_data = substr($o,0,-1);

        $res = request_post($url, $post_data);
        $res = json_decode($res,true);
        $token = $res['access_token'];
        Db::table('up_token')->where('id',4)->update([
            'token' => $token,
            'tdate' => $today_20
        ]);
        return $token;
    }else{
        return $tokenInfo['token'];
    }
}
 function request_post($url = '', $param = '')
{
    header('Access-Control-Allow-Origin: *');
    if (empty($url) || empty($param)) {
        return false;
    }

    $postUrl = $url;
    $curlPost = $param;
    // 初始化curl
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $postUrl);
    curl_setopt($curl, CURLOPT_HEADER, 0);
    // 要求结果为字符串且输出到屏幕上
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    // post提交方式
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
    // 运行curl
    $data = curl_exec($curl);
    curl_close($curl);

    return $data;
}